<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of carts_controller
 *
 * @author Spyros
 */
class CartsController extends AppController {

    var $uses = array();

    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('*');
    }

    function add($id) {
        if (!$this->Session->check('cart')) {
            $cart = array();
        } else {
            $cart = $this->Session->read('cart');
        }
        if (!array_key_exists($id, $cart)) {
            $cart[$id] = 1;
        } else {
            $cart[$id] = $cart[$id]+1;
        }
        $this->Session->write('cart', $cart);
//        $this->set('result', $id);
//        $this->set('result2', $cart[$id]);
//        $this->set('result3', $cart);
        $this->redirect(array('action' => 'index'));
    }

    function index() {
        if (!$this->Session->check('cart')) {
            $cart = array();
        } else {
            $cart = $this->Session->read('cart');
        }
        $result = array();
        $this->loadModel('Product');
        foreach ($cart as $product_id => $quantity) {
            $product = $this->Product->find('first', array('conditions' => array('Product.id' => $product_id)));
            array_push($result, array(
                'id' => $product['Product']['id'],
                'category' => $product['Category']['name'],
                'name' => $product['Product']['name'],
                'price' => $product['Product']['price'],
                'quantity' => $quantity
            ));
        }
        $this->set('result', $result);
    }

    function delete($id) {
        $cart = $this->Session->read('cart');
        unset($cart[$id]);
        $this->Session->write('cart', $cart);
        $this->redirect(array('action' => 'index'));
    }

    function deleteall() {
        $cart = $this->Session->read('cart');
        foreach ($cart as $i => $value) {
            unset($cart[$i]);
        }
        $this->Session->write('cart', $cart);
        $this->redirect(array('action' => 'index'));
    }

    function addone($id) {
        $cart = $this->Session->read('cart');
        $cart[$id] = $cart[$id]+1;
        $this->Session->write('cart', $cart);
        $this->redirect(array('action' => 'index'));
    }

    function removeone($id) {
        $cart = $this->Session->read('cart');
        $cart[$id] = $cart[$id]-1;
        $this->Session->write('cart', $cart);
        $this->redirect(array('action' => 'index'));
    }

}

?>
